import "package:ct_pa_majordomo/pages/mine/withdraw/api.dart";
import "package:flutter/material.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/utils/index.dart";

class WithdrawBillListPage extends StatefulWidget {
  final int withdrawId;
  const WithdrawBillListPage({super.key, required this.withdrawId});

  @override
  State<WithdrawBillListPage> createState() => _WithdrawBillListPageState();
}

class _WithdrawBillListPageState extends State<WithdrawBillListPage> {
  List _billList = [];
  bool _isLoading = true;
  bool _isLoadingMore = false;
  bool _hasMore = true;
  int _currentPage = 1;
  final int _pageSize = 20;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadBillList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  // 滚动监听
  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 200) {
      if (!_isLoadingMore && _hasMore) {
        _loadMore();
      }
    }
  }

  // 加载关联账单列表
  void _loadBillList() {
    setState(() {
      _isLoading = true;
    });

    withdrawApi.withdrawBillList(widget.withdrawId, queryParams: {
      "pageNum": 1,
      "pageSize": _pageSize,
    }).then((value) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _billList = value["rows"] ?? [];
          _currentPage = 1;
          _hasMore = (value["rows"] ?? []).length < (value["total"] ?? 0);
        });
      }
    }).catchError((error) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  // 加载更多数据
  void _loadMore() {
    if (_isLoadingMore || !_hasMore) return;

    setState(() {
      _isLoadingMore = true;
    });

    withdrawApi.withdrawBillList(widget.withdrawId, queryParams: {
      "pageNum": _currentPage + 1,
      "pageSize": _pageSize,
    }).then((value) {
      if (mounted) {
        final newRows = value["rows"] ?? [];
        setState(() {
          _isLoadingMore = false;
          _billList.addAll(newRows);
          _currentPage++;
          _hasMore = _billList.length < (value["total"] ?? 0);
        });
      }
    }).catchError((error) {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    });
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    _loadBillList();
  }

  // 获取账单类型图标
  IconData _getBillTypeIcon(String billType) {
    switch (billType) {
      case "rent":
        return Icons.home;
      case "utilities":
        return Icons.electric_bolt;
      case "deposit":
        return Icons.security;
      default:
        return Icons.receipt;
    }
  }

  // 获取账单类型文本
  String _getBillTypeText(String billType) {
    switch (billType) {
      case "rent":
        return "房租";
      case "utilities":
        return "水电费";
      case "deposit":
        return "押金";
      default:
        return "其他";
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "关联账单",
      child: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _billList.isEmpty
              ? RefreshIndicator(
                  onRefresh: _onRefresh,
                  child: ListView(
                    children: [
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.6,
                        child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.receipt_long,
                                size: 64,
                                color: ThemeVars.colorTextTer,
                              ),
                              const SizedBox(height: 16),
                              const Text(
                                "暂无关联账单",
                                style: TextStyle(
                                  color: ThemeVars.colorTextSec,
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              : RefreshIndicator(
                  onRefresh: _onRefresh,
                  child: ListView.builder(
                    controller: _scrollController,
                    padding: const EdgeInsets.all(ThemeVars.paddingPage),
                    itemCount: _billList.length + (!_hasMore ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == _billList.length) {
                        return _buildLoadingMore();
                      }
                      final bill = _billList[index];
                      return _buildBillItem(bill);
                    },
                  ),
                ),
    );
  }

  // 构建加载更多指示器
  Widget _buildLoadingMore() {
    if (!_hasMore) {
      return Container(
        padding: const EdgeInsets.all(16),
        child: const Center(
          child: Text(
            "没有更多数据了",
            style: TextStyle(
              color: ThemeVars.colorTextSec,
              fontSize: 14,
            ),
          ),
        ),
      );
    }
    return Container(
      padding: const EdgeInsets.all(16),
      child: Center(
        child: _isLoadingMore
            ? const CircularProgressIndicator()
            : const Text(
                "上拉加载更多",
                style: TextStyle(
                  color: ThemeVars.colorTextSec,
                  fontSize: 14,
                ),
              ),
      ),
    );
  }

  // 构建账单项
  Widget _buildBillItem(Map<String, dynamic> bill) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: ThemeVars.colorBorder,
          width: 0.5,
        ),
      ),
      child: Row(
        children: [
          // 左侧图标
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: ThemeVars.colorPrimary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              _getBillTypeIcon(bill["billType"] ?? ""),
              color: ThemeVars.colorPrimary,
              size: 20,
            ),
          ),
          const SizedBox(width: 12),
          
          // 中间内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      bill["name"] ?? "",
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: ThemeVars.colorPrimary.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        _getBillTypeText(bill["billType"] ?? ""),
                        style: const TextStyle(
                          fontSize: 12,
                          color: ThemeVars.colorPrimary,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
                Text(
                  bill["createTime"] ?? "",
                  style: const TextStyle(
                    fontSize: 12,
                    color: ThemeVars.colorTextSec,
                  ),
                ),
                if (bill["remark"] != null && bill["remark"].isNotEmpty) ...[
                  const SizedBox(height: 4),
                  Text(
                    "备注: ${bill["remark"]}",
                    style: const TextStyle(
                      fontSize: 12,
                      color: ThemeVars.colorTextSec,
                    ),
                  ),
                ],
              ],
            ),
          ),
          
          // 右侧金额
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                "¥${Utils.formatCurrency(bill["money"] ?? 0)}",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: ThemeVars.colorSuccess,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                "账单金额",
                style: const TextStyle(
                  fontSize: 12,
                  color: ThemeVars.colorTextSec,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
} 